<?php

namespace Shop\AdminBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Shop\AdminBundle\Controller\BaseController;

use Shop\AdminBundle\Entity\Shop;
use Shop\AdminBundle\Form\ShopType;

/**
 * @Route("/admin/shop")
 */
class ShopController extends BaseController
{

    /**
     * @Route("/", name="admin_shop")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        return $this->paginate($this->getRepo('shop'));
    }

    /**
     * 添加门店，表单处理
     *
     * @Route("/", name="admin_shop_create")
     * @Method("POST")
     * @Template("ShopAdminBundle:Shop:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Shop();
        $form = $this->createForm(new ShopType(), $entity, array(
            'action' => $this->generateUrl('admin_shop_create'),
            'method' => 'POST',
        ));

        $form->handleRequest($request);

        //TODO:添加可选字段
        $optional=array('address', 'latitude', 'longitude',
                        'picture','intro','star', 'contact', 'workTime');
        $this->setOptional($entity, $optional);

        if ($form->isValid()) {
            //图片处理
            $logoFile=$entity->getPicture();
            $fileName=$this->handleUpload($logoFile);
            $entity->setPicture($fileName);

            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_shop'));
        }

        return $this->redirect($this->generateUrl('admin_shop_new'));
    }

    /**
     * 添加门店页面
     *
     * @Route("/new", name="admin_shop_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Shop();
        $form = $this->createForm(new ShopType(), $entity, array(
            'action' => $this->generateUrl('admin_shop_create'),
            'method' => 'POST',
        ));

        $brandList=$this->getAvailableList('brand');

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
            'brandList'=>$brandList,
            'has_upload'=>true,
            'ajax_form'=>true
        );
    }

    /**
     * 更新门店页面
     *
     * @Route("/{id}/edit", name="admin_shop_edit")
     * @Method("GET")
     * @Template("ShopAdminBundle:Shop:new.html.twig")
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ShopAdminBundle:Shop')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Shop entity.');
        }

        $editForm = $this->createForm(new ShopType(), $entity, array(
            'action' => $this->generateUrl('admin_shop_update', array('id' => $entity->getId())),
            'method' => 'POST',
        ));

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'brandList'=>$this->getAvailableList('brand'),
            'is_edit'=>true,
            'ajax_form'=>true
        );
    }

    /**
     * 更新门店，表单处理
     *
     * @Route("/{id}", name="admin_shop_update")
     * @Method("POST")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('ShopAdminBundle:Shop')->find($id);

        $editForm = $this->createForm(new ShopType(), $entity, array(
            'action' => $this->generateUrl('admin_shop_update', array('id' => $entity->getId())),
            'method' => 'POST',
        ));

        $formName=$editForm->getName();
        $fileBag=$request->files->get($formName);

        if(!isset($fileBag['picture'])){
            $originFileName=$entity->getPicture();
        }

        $editForm->handleRequest($request);

        if ($editForm->isValid()) {

            if(isset($originFileName)){
                $entity->setPicture($originFileName);
            }
            else{
                $picFile=$entity->getPicture();
                $fileName= $this->handleUpload($picFile);
                $entity->setPicture($fileName);
            }

            //post filter
            $entity->setStar(floatval($entity->getStar()));
            $entity->setIsAudit(intval($entity->getIsAudit()));
            $entity->setOrderWeight(intval($entity->getOrderWeight()));

            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);

            $em->flush();

            return $this->redirect($this->generateUrl('admin_shop'));
        }
    }

    /**
     * Deletes a Shop entity.
     *
     * @Route("/{id}/delete", name="admin_shop_delete")
     * @Method("GET")
     */
    public function deleteAction(Request $request, $id)
    {
        return $this->deleteRow('shop',$request, $id);
    }

}
